package com.yongxing.plugintwo;

import android.annotation.SuppressLint;
import android.app.Application;
import android.content.res.AssetManager;
import android.content.res.Resources;
import android.content.res.XmlResourceParser;
import android.os.Environment;
import android.util.Log;

import java.lang.reflect.Method;

/**
 * Created by Mr.J on 2019/8/12.
 * 描述：
 */
public class App extends Application {

    private AssetManager mAssetManager;
    private Resources mNewResource;

    @SuppressLint("ResourceType")
    @Override
    public void onCreate() {
        super.onCreate();
        try {
            String apkPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/plugin-debug.apk";
            mAssetManager = AssetManager.class.newInstance();
            Method addAssetPathMethod = mAssetManager.getClass().getDeclaredMethod("addAssetPath", String.class);
            addAssetPathMethod.setAccessible(true);
            addAssetPathMethod.invoke(mAssetManager, apkPath);
//        手动实例化
            Method addOverlayPath = AssetManager.class.getDeclaredMethod("addOverlayPath", String.class);
            addOverlayPath.setAccessible(true);
            addOverlayPath.invoke(mAssetManager, apkPath);
//            插件的StringBloac被实例化了
            Resources supResource = getResources();
            mNewResource = new Resources(mAssetManager, supResource.getDisplayMetrics(), supResource.getConfiguration());

            XmlResourceParser layout = mNewResource.getLayout(2131296284);
            Log.e("jiang", "onCreate:" + layout);
        } catch (Exception e) {
            Log.e("jiang", "onCreate:" + e.toString());
            e.printStackTrace();
        }
    }

    @Override
    public AssetManager getAssets() {
        Log.e("jiang", "getAssets:" + mAssetManager);
        return mAssetManager == null ? super.getAssets() : mAssetManager;
    }

    @Override
    public Resources getResources() {
        Log.e("jiang", "getResources:" + mNewResource);
        return mNewResource == null ? super.getResources() : mNewResource;
    }
}
